<template>
  <view class="container">
    <!-- <u-navbar title="实名认证" :autoBack="true"></u-navbar> -->
    
    <view class="content">
      <u-form :model="form" :rules="rules" ref="uForm" labelWidth="120">
        <!-- 姓名 -->
        <u-form-item label="真实姓名" prop="name" borderBottom>
          <u-input 
            v-model="form.name" 
            placeholder="请输入与身份证一致的真实姓名" 
            border="none"
          ></u-input>
        </u-form-item>
        
        <!-- 身份证号 -->
        <u-form-item label="身份证号码" prop="idCard" borderBottom>
          <u-input 
            v-model="form.idCard" 
            placeholder="请输入身份证号码" 
            border="none"
            type="idcard"
          ></u-input>
        </u-form-item>
        
        <!-- 身份证正面 -->
        <u-form-item label="身份证人像面" prop="frontImage" required>
          <u-upload
            :fileList="frontImageList"
            @afterRead="afterFrontRead"
            @delete="deleteFrontImage"
            name="frontImage"
            :maxCount="1"
            width="200"
            height="120"
            :previewFullImage="true"
          >
            <image 
              v-if="!frontImageList.length" 
              src="@/static/id-card-front.jpg" 
              mode="aspectFill" 
              class="upload-placeholder"
            ></image>
          </u-upload>
          <view class="upload-tips">请上传身份证人像面照片</view>
        </u-form-item>
        
        <!-- 身份证反面 -->
        <u-form-item label="身份证国徽面" prop="backImage" required>
          <u-upload
            :fileList="backImageList"
            @afterRead="afterBackRead"
            @delete="deleteBackImage"
            name="backImage"
            :maxCount="1"
            width="200"
            height="120"
            :previewFullImage="true"
          >
            <image 
              v-if="!backImageList.length" 
              src="@/static/id-card-back.jpg" 
              mode="aspectFill" 
              class="upload-placeholder"
            ></image>
          </u-upload>
          <view class="upload-tips">请上传身份证国徽面照片</view>
        </u-form-item>
        
        <!-- 人脸识别 -->
        <u-form-item label="人脸识别" prop="faceImage" required>
          <view class="face-recognition" @click="startFaceRecognition">
            <image 
              v-if="form.faceImage" 
              :src="form.faceImage" 
              mode="aspectFill" 
              class="face-image"
            ></image>
            <view v-else class="face-placeholder">
              <u-icon name="camera-fill" size="40" color="#999"></u-icon>
              <text>点击进行人脸识别</text>
            </view>
          </view>
          <view class="upload-tips">请确保光线充足，正对摄像头</view>
        </u-form-item>
      </u-form>
      
      <u-button 
        type="primary" 
        @click="submit" 
        :loading="loading" 
        shape="circle" 
        class="submit-btn"
        :disabled="!formComplete"
      >
        提交认证
      </u-button>
      
      <u-toast ref="uToast"></u-toast>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      loading: false,
      form: {
        name: '',
        idCard: '',
        frontImage: '',
        backImage: '',
        faceImage: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' },
          { 
            validator: (rule, value, callback) => {
              if (!/^[\u4e00-\u9fa5]{2,10}$/.test(value)) {
                callback(new Error('请输入2-10个中文字符'));
              } else {
                callback();
              }
            }, 
            trigger: 'blur' 
          }
        ],
        idCard: [
          { required: true, message: '请输入身份证号码', trigger: 'blur' },
          { 
            validator: (rule, value, callback) => {
              if (!/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value)) {
                callback(new Error('请输入正确的身份证号码'));
              } else {
                callback();
              }
            }, 
            trigger: 'blur' 
          }
        ]
      },
      frontImageList: [],
      backImageList: []
    };
  },
  computed: {
    formComplete() {
      return this.form.name && 
             this.form.idCard && 
             this.form.frontImage && 
             this.form.backImage && 
             this.form.faceImage;
    }
  },
  methods: {
    // 身份证正面图片上传
    afterFrontRead(event) {
      this.uploadImage(event.file, 'front').then(url => {
        this.frontImageList = [{ url }];
        this.form.frontImage = url;
      });
    },
    
    // 身份证反面图片上传
    afterBackRead(event) {
      this.uploadImage(event.file, 'back').then(url => {
        this.backImageList = [{ url }];
        this.form.backImage = url;
      });
    },
    
    // 删除正面图片
    deleteFrontImage() {
      this.frontImageList = [];
      this.form.frontImage = '';
    },
    
    // 删除反面图片
    deleteBackImage() {
      this.backImageList = [];
      this.form.backImage = '';
    },
    
    // 图片上传方法
    uploadImage(file, type) {
      return new Promise((resolve, reject) => {
        uni.showLoading({
          title: '上传中...'
        });
        
        // 这里应该是实际的上传逻辑
        // 模拟上传过程
        setTimeout(() => {
          uni.hideLoading();
          const mockUrl = `https://example.com/upload/${type}_${Date.now()}.jpg`;
          resolve(mockUrl);
          
          // 实际项目中替换为:
          // uni.uploadFile({
          //   url: '你的上传接口',
          //   filePath: file[0].url,
          //   name: 'file',
          //   success: (res) => {
          //     const data = JSON.parse(res.data);
          //     resolve(data.url);
          //   },
          //   fail: reject
          // });
        }, 1000);
      });
    },
    
    // 开始人脸识别
    startFaceRecognition() {
      uni.showActionSheet({
        itemList: ['拍照识别', '从相册选择'],
        success: (res) => {
          const sourceType = res.tapIndex === 0 ? ['camera'] : ['album'];
          
          uni.chooseImage({
            count: 1,
            sourceType: sourceType,
            success: (res) => {
              this.uploadImage([{ url: res.tempFilePaths[0] }], 'face').then(url => {
                this.form.faceImage = url;
              });
            }
          });
        }
      });
      
      // 实际项目中可以接入专业的人脸识别SDK
      // 例如：
      // uni.navigateTo({
      //   url: '/pages/face-recognition'
      // });
    },
    
    // 提交认证
    submit() {
      this.$refs.uForm.validate().then(valid => {
        if (valid) {
          this.loading = true;
          
          // 模拟提交认证
          setTimeout(() => {
            this.loading = false;
            this.$refs.uToast.show({
              type: 'success',
              message: '实名认证成功',
              complete() {
                uni.navigateBack();
              }
            });
            
            // 实际项目中：
            // this.$http.post('/api/realname/auth', this.form)
            //   .then(res => {
            //     uni.$emit('authSuccess');
            //     uni.navigateBack();
            //   })
            //   .catch(err => {
            //     this.$refs.uToast.show({
            //       type: 'error',
            //       message: err.message || '认证失败'
            //     });
            //   })
            //   .finally(() => {
            //     this.loading = false;
            //   });
          }, 1500);
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  height: 100vh;
  background-color: #f8f8f8;
  
  .content {
    padding: 20rpx;
  }
  
  .upload-placeholder {
    width: 200rpx;
    height: 120rpx;
    border-radius: 8rpx;
    background-color: #f5f5f5;
  }
  
  .upload-tips {
    font-size: 24rpx;
    color: #999;
    margin-top: 10rpx;
  }
  
  .face-recognition {
    width: 200rpx;
    height: 200rpx;
    border-radius: 8rpx;
    background-color: #f5f5f5;
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden;
    
    .face-image {
      width: 100%;
      height: 100%;
    }
    
    .face-placeholder {
      display: flex;
      flex-direction: column;
      align-items: center;
      color: #999;
      font-size: 24rpx;
      
      text {
        margin-top: 10rpx;
      }
    }
  }
  
  .submit-btn {
    margin-top: 40rpx;
  }
}
</style>